package com.xinghou.mq.impl;

import com.spatial4j.core.context.SpatialContext;
import com.xinghou.mq.StoreInterface;
import com.xinghou.platform.dao.main.CityDAO;
import com.xinghou.platform.dao.main.StoreDAO;
import com.xinghou.platform.dao.main.UserDAO;
import com.xinghou.platform.dao.main.UserGeoDAO;
import com.xinghou.platform.lucene.main.StoreLuceneService;
import com.xinghou.platform.model.main.Store;
import org.apache.log4j.Logger;
import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree;
import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Closeable;
import java.io.IOException;

@Service("mqStoreService")
public class StoreInterfaceImpl implements StoreInterface, Closeable {
	private static Logger logger = Logger.getLogger(StoreInterfaceImpl.class);

	@Resource
	private UserDAO userDAO;
	@Resource
	private UserGeoDAO userGeoDAO;
	@Resource
	private CityDAO cityDAO;
	@Resource
	private StoreDAO storeDAO;
	@Resource
	private StoreLuceneService storeLuceneService;

	public StoreInterfaceImpl() {

	}

	public static final double RATE_MILE_TO_KM = 1.609344; // 英里和公里的比率
	public static final String LAT_FIELD = "lat";
	public static final String LON_FIELD = "lng";

	private SpatialContext ctx = SpatialContext.GEO;// "ctx" is the conventional
													// variable name
	int maxLevels = 11;
	SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);

	@Override
	public void update(int storeid, boolean update) {
		Store store = storeDAO.getStoreBystoreId(storeid);
		if(store==null){
			logger.error("user is null ;storeId="+storeid+";update="+update);
			return ;
		}
		
		try {
			if (update) {
				storeLuceneService.updateStore(store);
			} else {
				storeLuceneService.saveStore(store);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("更新门店Lucene失败", e);
			//throw new RuntimeException(e);
		}

	}

	@Override
	public void close() throws IOException {

	}

}
